<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-button size="default" type="primary" @click="handleAdd">新增</el-button>

      <div class="flex justify-between mt-4 mb-4">
        <div class="flex justify-end items-center">
          <div class="flex items-center mr-4">
            <span class="item">奖励ID：</span>
            <el-input v-model="listQuery.id" clearable placeholder="请输入奖励ID" size="normal"></el-input>
          </div>
          <div class="flex items-center mr-4">
            <span class="item">奖励名称：</span>
            <el-input v-model="listQuery.name" clearable placeholder="请输入奖励名称" size="normal"></el-input>
          </div>
          <div class="flex items-center mr-4">
            <span>状态：</span>
            <el-select v-model="listQuery.is_open"
                       class="filter-item"
                       filterable
                       placeholder="请选择状态"
                       style="width: 200px"
            >
              <el-option
                v-for="item in selectList2"
                :key="item.key"
                :label="item.lab"
                :value="item.key"
              ></el-option>
            </el-select>

          </div>
          <el-button size="default" type="primary" @click="getTableData">搜索</el-button>
          <el-button size="default" type="primary" @click="handleReset">重置</el-button>
        </div>
      </div>


      <el-table
        ref="multipleTable"
        v-loading="loading"
        :data="tableData"
        border
        class="mt-3"
        stripe
        style="width: 100%"
        tooltip-effect="dark"
      >
        <!-- <el-table-column :index="indexMethod" label="序号" prop="user_code" type="index" width="120px"></el-table-column> -->
        <el-table-column label="奖励ID" prop="id"></el-table-column>
        <el-table-column label="奖励名称" prop="detail.name"></el-table-column>
        <el-table-column label="奖励图片" prop="detail.picture">
          <template slot-scope="scoped">
            <el-image :lazy="true" :src="scoped.row.detail.picture" class="imageStyle" fit="fill"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="奖励价值" prop="detail.price">
          <template slot-scope="{row}">
            {{ row.reward_type === 'gift' ? row.detail.price : '--'}}
          </template>
        </el-table-column>
        <el-table-column label="奖励有效期" prop="prize.count">
          <template slot-scope="{row}">
            {{ row.reward_type === 'gift' ? '--' : row.prize.count}}
          </template>
        </el-table-column>
        <el-table-column label="关联碎片" prop="chip.name"></el-table-column>
        <el-table-column label="兑换所需碎片数" prop="count"></el-table-column>
        <el-table-column label="排序" prop="sort"></el-table-column>
        <el-table-column label="更新时间" prop="updated_at"></el-table-column>
        <el-table-column label="状态" prop="is_open">
          <template slot-scope="{row}">
            <el-tag v-if="row.is_open === 1" type="success">启用</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleOpen(scope.row)"
            >{{ scope.row.is_open === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleEdit(scope.row)"
            >编辑
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleSDelete(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <cus-pagination
        v-show="total > 0"
        :limit.sync="listQuery.perPage"
        :page.sync="listQuery.page"
        :total="total"
        @pagination="getTableData"
      />
    </el-card>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%"
      @close="closeDialog"
    >
      <el-form ref="form" :inline="false" :model="formData" :rules="rules" label-width="150px" size="normal">
        <el-form-item label="选择奖励" prop="prize_id">
          <el-select v-model="formData.prize_id" value-key="" placeholder="请选择" clearable filterable>
            <el-option v-for="item in options"
              :key="item.prize_id"
              :label="item.title"
              :value="item.prize_id">
              <el-popover placement="right" trigger="hover">
                <img :src="item.icon" alt="" style="max-width: 200px;max-height: 200px">
                <p slot="reference">{{ item.title }}</p>
              </el-popover>
            </el-option>
          </el-select>
          
        </el-form-item>
        <el-form-item label="关联碎片" prop="chip_id">
          <el-select v-model="formData.chip_id" value-key="" placeholder="请选择" clearable filterable>
            <el-option v-for="item in options2"
              :key="item.id"
              :label="item.name"
              :value="item.id">
              <el-popover placement="right" trigger="hover">
                <img :src="item.icon" alt="" style="max-width: 200px;max-height: 200px">
                <p slot="reference">{{ item.name }}</p>
              </el-popover>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="锻造所需碎片数" prop="count">
          <el-input
            type="number"
            v-model="formData.count"
            placeholder="请输入锻造所需碎片数"
            @input="handleInput2"
          />
        </el-form-item>
        
        <el-form-item label="排序" prop="sort">
          <el-input
            type="number"
            v-model="formData.sort"
            placeholder="请输入排序"
            @input="handleInput"
          />
        </el-form-item>
        <el-form-item label="状态" prop="">
          <el-radio-group v-model="formData.is_open">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <span slot="footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleOnSubmit">确定</el-button>
            </span>
    </el-dialog>

  </div>
</template>

<script>
import { chipExchangeList, chipExchangeAdd, chipExchangeEdit, chipExchangeChange, poolPrizeList, chipList } from '@/api/sunGame/sunGame'

export default {
  name: 'normalConfig',
  components: {},
  data() {
    return {
      selectList2: [
        { key: -1, lab: '全部状态' },
        { key: 1, lab: '启用 ' },
        { key: 2, lab: '禁用' }
      ],
      dialogVisible: false,
      dialogVisible2: false,
      formData: {
        chip_id: undefined,
        prize_id: undefined,
        count: undefined,
        is_open: 1,
        sort: undefined,
        id: undefined
      },
      rules: {
        chip_id: [{ required: true, message: '请选择关联碎片', trigger: 'blur' }],
        prize_id: [{ required: true, message: '请选择奖励', trigger: 'blur' }],
        count: [{ required: true, message: '请输入锻造所需碎片数', trigger: 'blur' }],
      },
      loading: false,
      tableData: [],
      listQuery: {
        page: 1,
        perPage: 10,
        id: undefined,
        name: undefined,
        is_open: undefined
      },
      total: 1,
      options: [],
      options2: [],
      fileList: [],
      dialogTitle: undefined
    }
  },
  created() {
    this.getTableData()
    this.getListData()
    this.getChipList()
  },
  methods: {
    indexMethod(index) {
      return this.total - (this.listQuery.page - 1) * this.listQuery.perPage - index
    },
    // 网络请求
    /**
     * getTableData
     * @desc 获取表格数据
     */
    async getTableData() {
      this.loading = true
      for (let key in this.listQuery) {
        this.listQuery[key] = !this.listQuery[key] ? undefined : this.listQuery[key]
      }
      const { data, code } = await chipExchangeList(this.listQuery)
      if (code === 200) {

        this.tableData = data.list
        this.total = data.meta.total
      }
      this.loading = false

    },
    async getListData() {
      try {
        const { data } = await poolPrizeList({
          page: 1,
          perPage: 1000,
          type: 1
        })
        const optArr = []
        data.list.map(item => {
          if(item.reward_type === 'product') {
            item.title = item.title + `(${item.count}天)`
          }else if(item.reward_type === 'gift') {
            item.title = item.title + `(${item.price}M豆)`
          }
          if(item.reward_type != "debris") {
            optArr.push(item)
          }
        })
        this.options = optArr
      } catch (e) {

      }
    },
    async getChipList() {
      const { data, code } = await chipList({
        page: 1,
        perPage: 1000
      })
      if (code === 200) {

        this.options2 = data.list
      }

    },
    closeDialog() {
      if (this.$refs['form']) {
        this.$refs['form'].clearValidate() // 清除整个表单的校验
        this.$refs['form'].resetFields() // 清除整个表单的校验
      }
      this.fileList = []
      this.formData = {
        chip_id: undefined,
        prize_id: undefined,
        count: undefined,
        is_open: 1,
        sort: undefined,
        id: undefined
      }
    },

    handleOnSubmit() {

      this.$refs['form'].validate(valid => {
        if (valid) {

          for (let key in this.formData) {
            this.formData[key] = !this.formData[key] ? 0 : this.formData[key]
          }
          if (this.formData.id) {
            chipExchangeEdit(this.formData).then(res => {
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: '操作成功'
                })
              }
              this.dialogVisible = false
              this.getTableData()
            })
          } else {
            chipExchangeAdd(this.formData).then(res => {
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: '操作成功'
                })
              }
              this.dialogVisible = false
              this.getTableData()
            })
          }

        }
      })
    },
    handleEdit(row) {
      this.dialogTitle = '编辑'
      this.formData = JSON.parse(JSON.stringify(row))
      this.fileList = [{
        url: row.icon
      }]
      this.dialogVisible = true
    },
    handleOpen(row) {
      this.$confirm(`确认${row.is_open === 1 ? '禁用' : '启用'}操作？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        chipExchangeChange({
          id: row.id,
          type: 1
        }).then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '操作成功'
            })
          }
          this.dialogVisible = false
          this.getTableData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    handleSDelete(row) {
      this.$confirm('此操作不可恢复，是否继续删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        chipExchangeChange({
          id: row.id,
          type: 0
        }).then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '操作成功'
            })
          }
          this.dialogVisible = false
          this.getTableData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleReset() {
      this.listQuery = {
        page: 1,
        perPage: 10,
        id: undefined,
        name: undefined,
        is_open: undefined
      }
      this.getTableData()
    },
    handleAdd() {
      this.dialogTitle = '新增'
      this.dialogVisible = true
    },
    handleInput(val) {
      if(val < 1) {
        this.formData.sort = undefined
      }
      if(val.includes('.')) {
        this.formData.sort = val.replace('.', '')
      }
    },
    handleInput2(val) {
      if(val < 1) {
        this.formData.count = undefined
      }
      if(val.includes('.')) {
        this.formData.count = val.replace('.', '')
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.infoBox {
  margin-top      : 15px;
  margin-bottom   : 15px;
  padding-bottom  : 15px;
  border          : 1px solid #999999;
  border-radius   : 10px;
  display         : flex;
  align-items     : baseline;
  justify-content : center;
  box-sizing      : border-box;
  padding-right   : 30px;

  .info_1 {
    display         : flex;
    justify-content : center;
    flex-direction  : column;
    width           : 100%;

    .info_2 {
      margin-top  : 15px;
      display     : flex;
      align-items : center;
      position    : relative;

      span {
        width      : 180px;
        text-align : right;
      }

      .tip {
        color     : red;
        font-size : 12px;
        position  : absolute;
        top       : 100%;
        left      : 120px;
      }
    }
  }
}

.item {
  width : 100px;
}

.formItemBox {
  display     : flex;
  align-items : center;
  flex-wrap   : wrap;

  width       : 100%;
  overflow    : hidden;
}

::v-deep {
  .formItemBox {
    .el-form-item {
      width : 50% !important;
    }
  }

}

</style>

